package com.silences.servlet;

import com.alibaba.fastjson.JSON;
import com.silences.pojo.Goods;
//import com.silences.pojo.User;
import com.silences.service.GoodsService;
//import com.silences.service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.ServerException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;


@WebServlet("/addGoods") //设置接口路径
public class AddGoodsServlet extends HttpServlet {
    //extends 继承 HttpServlet类

    //get 请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp){

    }


    //post 请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServerException,IOException {

        //post 请求优点  1 接收的数据量比较大  2 数据相对安全的

        //获取前端传递参数
        String goodsname=req.getParameter("goodsname");
        String goodsprice=req.getParameter("goodsprice");
        String goodstype=req.getParameter("goodstype");
        String avatar=req.getParameter("avatar");
        String createdate=req.getParameter("createdate");


        //组装成对象
        Goods goods =new Goods();
        goods.setGoodsname(goodsname);//通过setter 方法给对象设值
        goods.setGoodsprice(goodsprice);
        goods.setGoodstype(goodstype);
        goods.setAvatar(avatar);
        //创建一个SimpleDateFormat()工具进行日期处理
        SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd");
        //字符串格式的日期经过转换之后给user赋值
        try {
            goods.setCreatedate(sf.parse(createdate));//try/catch 异常抓取，进行异常处理
        } catch (ParseException e) { //ParseException 转换异常
            e.printStackTrace();
        }

        //调用业务层方法
        GoodsService goodsService =new GoodsService();
        try {
            Map<String,Object> map = goodsService.addGoodss(goods);
            //返回数据给前端
            resp.getWriter().write(JSON.toJSON(map).toString());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
